import React, { useEffect, useState } from 'react'
import { useParams } from 'react-router-dom'
import {
  Card,
  Row,
  Col,
  Tree,
  Tag,
  Pagination,
  Table,
  Button,
  message,
} from 'antd'
import type { DataNode, TreeProps } from 'antd/es/tree'
import {
  IdepList,
  IscheduleList,
  IscheduleTableList,
} from '@api/hospital/hospitalList/model/hospitalListTypes'
import {
  reqGetDepList,
  reqGetScheduleRule,
  reqGetScheduleTable,
} from '@api/hospital/hospitalList'
const treeData: DataNode[] = [
  {
    title: 'parent 1',
    key: '0-0',
    children: [
      {
        title: 'parent 1-0',
        key: '0-0-0',
        disabled: true,
        children: [
          {
            title: 'leaf',
            key: '0-0-0-0',
            disableCheckbox: true,
          },
          {
            title: 'leaf',
            key: '0-0-0-1',
          },
        ],
      },
      {
        title: 'parent 1-1',
        key: '0-0-1',
        children: [
          {
            title: <span style={{ color: '#1890ff' }}>sss</span>,
            key: '0-0-1-0',
          },
        ],
      },
    ],
  },
]
let depcode: string
export default function HospitalSchedule() {
  const hoscode = useParams().hoscode as string
  // 所有科室数据
  const [depList, setDepList] = useState<IdepList>([])
  // 所有一级科室的depcode
  const [topDepcode, setTopDepcode] = useState<string[]>([])
  // 排班规则
  const [scheduleRule, setScheduleRule] = useState<IscheduleList>([])

  // 分页
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(5)
  const [total, setTotal] = useState(0)

  // 面包屑效果对应的状态
  const [hosname, setHosname] = useState('')
  const [depname, setDepname] = useState('')
  const [workDate, setWorkDate] = useState('')

  // 排班表格数据
  const [scheduleTable, setScheduleTable] = useState<IscheduleTableList>([])

  useEffect(() => {
    // 组件挂载获取所有科室数据
    async function fetch() {
      // 注意: 一个异步函数返回值是promise.当这个异步函数中所有的代码执行完毕,则返回的promise的状态变成成功
      depcode = await getDepList() //获取科室
      const workDate = await getScheduleRules(page, pageSize, depcode) //排班规则
      getScheduleTable(workDate) //排班表格
    }
    fetch()
  }, [])

  // 获取科室数据的函数
  async function getDepList() {
    const result = await reqGetDepList(hoscode as string)
    // 禁用一级科室,所以拿到数据之后,先给所以一级科室添加disabled:true.然后在赋值给状态
    result.forEach((item) => {
      item.disabled = true
    })
    setDepList(result)
    // 获取所有的一级科室的depcode.存储到一个新数组中
    setTopDepcode(result.map((item) => item.depcode))
    // 获取科室名称
    setDepname(result[0].children[0].depname)
    // 注意: 异步函数中返回什么.异步函数的promise成功之后,value属性就指向什么
    return result[0].children[0].depcode
  }

  // 获取排班规则的函数
  async function getScheduleRules(
    page: number,
    pageSize: number,
    depcode: string
  ) {
    const result = await reqGetScheduleRule(page, pageSize, hoscode, depcode)

    setScheduleRule(result.bookingScheduleList)
    setHosname(result.baseMap.hosname)
    setWorkDate(result.bookingScheduleList[0]?.workDate)
    setTotal(result.total)
    return result.bookingScheduleList[0]?.workDate
  }

  // 获取排班表格数据
  async function getScheduleTable(workDate: string) {
    try {
      const result = await reqGetScheduleTable(hoscode, depcode, workDate)
      // console.log(result)
      setScheduleTable(result)
    } catch (error) {
      message.error('当前科室暂无数据!!')
    }
  }

  const onSelect: TreeProps['onSelect'] = async (selectedKeys, info) => {
    // console.log('selected', selectedKeys, info)
    // 排班规则
    let code = selectedKeys[0] as string
    depcode = code // 修改全局的科室编码
    const workDate = await getScheduleRules(page, pageSize, code) //重新获取新科室的排班规则
    // 获取排班表格数据
    getScheduleTable(workDate)
  }

  const columns = [
    {
      title: '序号',
      render(a: any, b: any, index: number) {
        return index + 1
      },
    },
    {
      title: '职称',
      dataIndex: 'title',
    },
    {
      title: '号源时间',
      dataIndex: 'workDate',
    },
    {
      title: '可预约数',
      dataIndex: 'availableNumber',
    },
    {
      title: '剩余预约数',
      dataIndex: 'reservedNumber',
    },
    {
      title: '挂号费(元)',
      dataIndex: 'amount',
    },
    {
      title: '擅长技能',
      dataIndex: 'skill',
    },
  ]

  // 计算tree父组件的高度
  //   视口高度-64-34-24*2-22-14
  const treeWrapperHeight =
    document.documentElement.clientHeight - 64 - 34 - 24 * 2 - 22 - 14

  return (
    <Card>
      <p>
        选择：{hosname} / {depname} / {workDate}
      </p>
      {/* Row和Col是antd中提供的栅格系统组件
      Row表示一行. 一行24份 gutter表示列之间的间隔. 值的单位是像素
      Col表示一列  span表示这一列占多少份
    
      */}
      <Row gutter={20}>
        <Col span={5}>
          <div
            style={{
              border: '1px solid #ccc',
              height: treeWrapperHeight,
              overflow: 'scroll',
            }}
          >
            <Tree
              //   checkable //显示复选框
              //   defaultExpandedKeys={topDepcode} // 默认展开的节点 注意:只在第一次解析时生效
              //   defaultSelectedKeys={['0-0-0', '0-0-1']} //默认选中的节点
              //   defaultCheckedKeys={['0-0-0', '0-0-1']} //默认复选框的节点
              onSelect={onSelect} // 点击节点的事件处理函数
              //   onCheck={onCheck} // 点击复选框的事件处理函数
              treeData={depList as any} // 树型结构要渲染的数据
              // 注意: Tree组件默认渲染treeData中的title和key.但是我们的数据没有这两个字段.所以我们要自定义要使用的字段是谁
              fieldNames={{
                title: 'depname',
                key: 'depcode',
              }}
              expandedKeys={topDepcode}
            />
          </div>
        </Col>
        <Col span={19}>
          {scheduleRule.map((item) => {
            return (
              <Tag
                key={item.workDate}
                color={item.workDate === workDate ? 'green' : ''}
                onClick={() => {
                  setWorkDate(item.workDate)
                  getScheduleTable(item.workDate)
                }}
              >
                <div>
                  {item.workDate} {item.dayOfWeek}
                </div>
                <div>
                  {item.availableNumber} / {item.reservedNumber}
                </div>
              </Tag>
            )
          })}

          <Pagination
            total={total}
            current={page}
            pageSize={pageSize}
            showSizeChanger={true}
            style={{ marginTop: 10, marginBottom: 10 }}
            onChange={async (page, pageSize) => {
              setPage(page)
              setPageSize(pageSize)
              const workDate = await getScheduleRules(page, pageSize, depcode)
              getScheduleTable(workDate)
            }}
          ></Pagination>

          <Table
            columns={columns}
            dataSource={scheduleTable}
            pagination={false} //表格不展示分页器
            rowKey="id"
          ></Table>

          <Button style={{ marginTop: 10 }}>返回</Button>
        </Col>
      </Row>
    </Card>
  )
}
